import * as map from "./map.js";

const divContainerEl = document.querySelector("#game");
const pieceWidth = 45;
const pieceHeight = 45;

function setDivContainer() {
  divContainerEl.style.width = pieceWidth * map.colNumber + "px";
  divContainerEl.style.height = pieceHeight * map.rowNumber + "px";
}

function setContent() {
  divContainerEl.innerHTML = "";
  for (let row = 0; row < map.rowNumber; row++) {
    for (let col = 0; col < map.colNumber; col++) {
      setOnePiece(row, col);
    }
  }
}

function isCorrect(row, col) {
  return map.correct.find((e) => e.row === row && e.col === col) !== undefined;
}

function setOnePiece(row, col) {
  const value = map.content[row][col];
  const divEl = document.createElement("div");
  divEl.className = "item";
  divEl.style.top = row * pieceHeight + "px";
  divEl.style.left = col * pieceWidth + "px";

  if (value === map.PLAYER) {
    divEl.classList.add("player");
  } else if (value === map.WALL) {
    divEl.classList.add("wall");
  } else if (value === map.BOX) {
    if (isCorrect(row, col)) {
      divEl.classList.add("correct-box");
    } else {
      divEl.classList.add("box");
    }
  } else {
    // 空白
    if (isCorrect(row, col)) {
      divEl.classList.add("correct");
    } else {
      return; // 只是一个普通空白
    }
  }

  divContainerEl.append(divEl);
}

export default function () {
  setDivContainer();
  setContent();
}
